package com.techyuan.intellij.tomcat.conf;

import com.intellij.ide.browsers.WebBrowser;
import com.intellij.ide.browsers.WebBrowserManager;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.techyuan.intellij.tomcat.setting.RunnerSetting;
import com.techyuan.intellij.tomcat.setting.TomcatInfo;
import com.techyuan.intellij.tomcat.setting.TomcatSettingConfigurable;
import org.apache.commons.lang.StringUtils;
import org.jdesktop.swingx.JXButton;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
import java.text.NumberFormat;
import java.util.Map;

/**
 * Author : zengkid
 * Date   : 2/16/2017
 * Time   : 3:15 PM
 */
public class TomcatSettingsEditor extends SettingsEditor<TomcatRunConfiguration> {
    private final Project project;
    private RunnerSetting runnerSetting;

    public TomcatSettingsEditor(TomcatRunConfiguration tomcatRunConfiguration, Project project) {
        runnerSetting = new RunnerSetting(project);
        this.project = project;
        //super.resetFrom(tomcatRunConfiguration);
    }

    @Override
    protected void resetEditorFrom(TomcatRunConfiguration tomcatRunConfiguration) {
        TomcatInfo tomcatInfo = tomcatRunConfiguration.getTomcatInfo();
        if (tomcatInfo != null) {
            runnerSetting.getTomcatField().getComboBox().setSelectedItem(tomcatInfo);
        }

        Module module = tomcatRunConfiguration.getModule(project);
        if (module != null) {
            runnerSetting.getDeployModule().setSelectedModule(module);
        }

        String customContext = tomcatRunConfiguration.getCustomContext();
        if (customContext != null && !"".equals(customContext.trim())) {

            runnerSetting.getCustomContextField().setText(customContext);
            runnerSetting.getCustomContextField().getTextField().setText(customContext);
        }

        String contextPath = tomcatRunConfiguration.getContextPath();
        if (contextPath != null && !"".equals(contextPath.trim())) {
            runnerSetting.getContextPathField().setText(contextPath);
        }
        String port = tomcatRunConfiguration.getPort();
        if (port != null && !"".equals(port.trim())) {
            runnerSetting.getPortField().setText(port);
        }
        String adminPort = tomcatRunConfiguration.getAdminPort();
        if (adminPort != null && !"".equals(adminPort.trim())) {
            runnerSetting.getAdminPort().setText(adminPort);
        }

        String vmOptions = tomcatRunConfiguration.getVmOptions();
        if (vmOptions != null && !"".equals(vmOptions.trim())) {
            runnerSetting.getVmOptions().setText(vmOptions);
        }

        Map<String, String> envOptions = tomcatRunConfiguration.getEnvOptions();
        if (envOptions != null && !envOptions.isEmpty()) {
            runnerSetting.getEnvOptions().setEnvs(envOptions);
        }

        Boolean passParentEnvs = tomcatRunConfiguration.getPassParentEnvironmentVariables();
        if (passParentEnvs != null) {
            runnerSetting.getEnvOptions().setPassParentEnvs(passParentEnvs);
        }

        String browserId = tomcatRunConfiguration.getBrowserId();
        if (StringUtils.isNotBlank(browserId)) {
            WebBrowser webBrowser = WebBrowserManager.getInstance().findBrowserById(browserId);
            runnerSetting.getOpenBrowser().setSelectedWebBrowser(webBrowser);
        }

    }

    @Override
    protected void applyEditorTo(TomcatRunConfiguration tomcatRunConfiguration) throws ConfigurationException {
        TomcatInfo selectedTomcat = (TomcatInfo) runnerSetting.getTomcatField().getComboBox().getSelectedItem();
        if (selectedTomcat != null) {
            tomcatRunConfiguration.setTomcatInfo(selectedTomcat);
        }

        tomcatRunConfiguration.setModule(runnerSetting.getModuleSelector().getModule());
        tomcatRunConfiguration.setCustomContext(runnerSetting.getCustomContextField().getText());
        tomcatRunConfiguration.setContextPath(runnerSetting.getContextPathField().getText());
        tomcatRunConfiguration.setPort(runnerSetting.getPortField().getText());
        tomcatRunConfiguration.setAdminPort(runnerSetting.getAdminPort().getText());
        tomcatRunConfiguration.setVmOptions(runnerSetting.getVmOptions().getText());
        tomcatRunConfiguration.setEnvOptions(runnerSetting.getEnvOptions().getEnvs());
        tomcatRunConfiguration.setPassParentEnvironmentVariables(runnerSetting.getEnvOptions().isPassParentEnvs());
        WebBrowser selectedBrowser = runnerSetting.getOpenBrowser().getSelectedWebBrowser();
        if (selectedBrowser != null) {
            tomcatRunConfiguration.setBrowserId(selectedBrowser.getId().toString());
        }
    }

    @NotNull
    @Override
    protected JComponent createEditor() {
        TextFieldWithBrowseButton customContextField = runnerSetting.getCustomContextField();
        JFormattedTextField portField = runnerSetting.getPortField();
        JFormattedTextField adminPort = runnerSetting.getAdminPort();
        JTextField contextPathField = runnerSetting.getContextPathField();

        JXButton configurationButton = runnerSetting.getConfigurationButton();
        configurationButton.addActionListener(e -> ShowSettingsUtil.getInstance().showSettingsDialog(project, TomcatSettingConfigurable.class));

        VirtualFile baseDir = VirtualFileManager.getInstance().getFileSystem("file").findFileByPath(project.getBasePath());
        customContextField.addBrowseFolderListener("Context xml", "Choose custom context xml file", project, FileChooserDescriptorFactory.createSingleFileDescriptor().withRoots(baseDir));

        portField.setValue(8080);
        adminPort.setValue(8005);
        DefaultFormatterFactory tf = new DefaultFormatterFactory();
        NumberFormat format = NumberFormat.getInstance();
        format.setGroupingUsed(false);
        NumberFormatter formatter = new NumberFormatter(format);
        formatter.setValueClass(Integer.class);
        formatter.setMinimum(0);
        formatter.setMaximum(65535);
        tf.setDefaultFormatter(formatter);
        portField.setFormatterFactory(tf);
        adminPort.setFormatterFactory(tf);

        contextPathField.setText("/");

        runnerSetting.getModuleSelector().reset();

        runnerSetting.getOpenBrowser().fillWebBrowsers();
        return runnerSetting.getMainPanel();
    }

}
